package com.hghivln.erpwarehouse.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hghivln.erpwarehouse.system.common.lang.Constant;
import com.hghivln.erpwarehouse.system.common.lang.DataGridlView;
import com.hghivln.erpwarehouse.system.common.lang.Result;
import com.hghivln.erpwarehouse.system.utils.MD5Utils;
import com.hghivln.erpwarehouse.system.entity.Dept;
import com.hghivln.erpwarehouse.system.entity.User;
import com.hghivln.erpwarehouse.system.mapper.UserMapper;
import com.hghivln.erpwarehouse.system.service.DeptService;
import com.hghivln.erpwarehouse.system.service.UserService;
import com.hghivln.erpwarehouse.system.utils.ApplicationContextUtil;
import com.hghivln.erpwarehouse.system.vo.UserVo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.List;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hghivln
 * @since 2021-06-21
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Override
    public User queryUserByLoginName(String username) {
        if (StringUtils.isEmpty(username)) {
            return null;
        }
        QueryWrapper<User> qw = new QueryWrapper<>();
        QueryWrapper<User> queryWrapper = qw.eq("loginname", username);
        // 如果条件不成立相当于执行select * from sys_user，所以不在里面设置条件
        return this.getBaseMapper().selectOne(queryWrapper);
    }

    @Override
    public DataGridlView queryAllUser(UserVo userVo) {
        Page<User> page = new Page<>(userVo.getPage(), userVo.getLimit());
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq(!StringUtils.isEmpty(userVo.getDeptid()),"deptid",userVo.getDeptid());
        qw.like(!StringUtils.isEmpty(userVo.getName()),"name",userVo.getName());
        qw.like(!StringUtils.isEmpty(userVo.getRemark()),"remark",userVo.getRemark());
        qw.eq(!StringUtils.isEmpty(userVo.getAddress()),"address",userVo.getAddress());
        getBaseMapper().selectPage(page,qw);
        DeptService deptService = ApplicationContextUtil.getBean(DeptService.class);
        List<User> records = page.getRecords();
        for (User record : records) {
            if (record.getDeptid()!=null){
                Dept dept = deptService.getById(record.getDeptid());
                record.setDeptname(dept.getName());
            }
        }
        return new DataGridlView(page.getTotal(),page.getRecords());
    }

    @Override
    public User addUser(User user) {
        getBaseMapper().insert(user);
        return user;
    }

    @Override
    public User updateUser(User user) {
        getBaseMapper().updateById(user);
        return user;
    }

    @Override
    public List<Integer> queryRoleIdsByUid(Integer uid) {
        return getBaseMapper().queryRoleIdsByUid(uid);
    }

    @Override
    public void saveUserRole(Integer uid, Integer[] rids) {
        // 防止主键冲突
        getBaseMapper().deletRoleUserById(uid);
        if (rids != null && rids.length > 0){
            for (Integer rid : rids) {
                getBaseMapper().saveUserRole(uid,rid);
            }
        }
    }

    @Override
    public void resetUserPwd(Integer id) {
        User user = getBaseMapper().selectById(id);
        user.setSalt(MD5Utils.createUUID());
        user.setPwd(MD5Utils.md5(Constant.USER_DEFALT_PWD,user.getSalt(),Constant.HASHITERATIONS));
        getBaseMapper().updateById(user);
    }

    @Override
    public Result changePassword(String oldPassword, String newPwdOne, String againPassword, Integer id) {
        User currentUser = getBaseMapper().selectById(id);
        // 通过用户输入的原密码，进行加密生成新的旧密码。
        String oldPwd = new Md5Hash(oldPassword, currentUser.getSalt(), Constant.HASHITERATIONS).toString();
        if (currentUser.getPwd().equals(oldPwd)){
            if (newPwdOne.equals(againPassword)){
                currentUser.setSalt(MD5Utils.createUUID());
                currentUser.setPwd(new Md5Hash(againPassword, currentUser.getSalt(), Constant.HASHITERATIONS).toString());
                getBaseMapper().updateById(currentUser);
                return Result.UPDATE_SUCCESS;
            }else {
                return Result.UPDATE_AGAINPWD_ERROR;
            }
        }else {
            return Result.UPDATE_PWD_ERROR;
        }
    }

    @Override
    public boolean removeById(Serializable id) {
        return super.removeById(id);
    }

    @Override
    public DataGridlView queryUserMaxOrderNum() {
        Integer maxOrderNum = getBaseMapper().queryUserMaxOrderNum();
        return new DataGridlView(maxOrderNum+1);
    }


}
